#!/bin/bash
#
#    al-tint2-session: a script to read a saved Tint2 session file
#     and start the tint2s
#    Copyright (C) 2015 damo    <damo@bunsenlabs.org>
#    Borrowed with love by arcolinux.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#   To start the chosen Tint2 session at login, add the following line
#   to config/openbox/autostart:
#
#      am-tint2-session
#
########################################################################
TINT2PATH="$HOME/.config/tint2"
SESSIONFILE="$TINT2PATH/tint2-sessionfile"
USAGE=$(
    echo -e "\vUSAGE:  with no command argument, the script uses the chosen"
    echo -e "\tTint2 session file \"$TINT2PATH/tint2-sessionfile\","
    echo -e "\tif it exists, otherwise the default tint2rc is used"
    echo -e "\v\tTo start them at login, add the following line to autostart:"
    echo -e "\v\t\am-tint2-session"
)

findArgs(){     # get command args
    for arg in "$@";do
        if [[ $1 = "-h" ]] || [[ $1 = "--help" ]];then
            echo "$USAGE"
            exit 0
        else
            echo -e "\tERROR: sorry I don't understand the input"
            echo "$USAGE"
            exit 0
        fi
    done
}

testSessionfile(){
    if test -f  "$1" &>/dev/null;then # sessionfile found
        killTints
        while read line;do
            tint2 -c "$line" &
            sleep 1s
        done < "$1"
    else
        echo -e "Created sessionfile \"$1\"\nRunning default tint2rc" 2>&1
        echo "$TINT2PATH/tint2rc" > "$SESSIONFILE"
        killTints
        tint2 -c "$TINT2PATH/tint2rc" &>/dev/null
    fi
}

killTints(){
    pgrep -a tint2 | while read pid cmd; do
        if [[ ${cmd%% *} = tint2 ]]; then
            kill "$pid"
        fi
    done
}

if [ $# -eq 0 ];then    # if no args, then run default sessionfile
    testSessionfile "$SESSIONFILE"
else
    findArgs "$@"
fi

# restart compositor in case of rendering problems
#am-compositor --restart

exit 0
